﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Schema;

namespace Landscape{
    public static class XmlDocumentExtensions {
        private static IList<string> _schemaValidationErrors;
        public static void LoadTrustedXml(this XmlDocument doc, string docNs, System.IO.StringReader xmlString, System.IO.StringReader xmlSchema) {
            _schemaValidationErrors = new List<string>();

            XmlReaderSettings settings = new XmlReaderSettings() {
                ValidationType = ValidationType.Schema,
            };
            settings.Schemas.Add(docNs, XmlReader.Create(xmlSchema));
            settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings;
            settings.ValidationEventHandler += new ValidationEventHandler(LoadTrustedXml_ValidationEventHandler);

            XmlReader reader = XmlReader.Create(xmlString, settings);
            try {
                doc.Load(reader);
            } catch (Exception ex) {
                throw new Exception("Exception occurred while validating configuration. " + ex.Message);
            } finally {
                reader.Close();
                xmlString.Close();
                xmlSchema.Close();
            }
        }

        private static void LoadTrustedXml_ValidationEventHandler(object sender, ValidationEventArgs e) {
            switch (e.Severity) {
                default:
                case XmlSeverityType.Error:
                    throw new Exception(e.Message);
                case XmlSeverityType.Warning:
                    _schemaValidationErrors.Add("[warning]" + e.Message);
                    break;
            }

        }
    }
}
